<template>
  <div class="task-form">
    <div class="page-header">
      <h2>{{ isEdit ? '编辑任务' : '新建任务' }}</h2>
      <a-button @click="goBack">
        <ArrowLeftOutlined />
        返回
      </a-button>
    </div>

    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      layout="vertical"
      @finish="handleSubmit"
    >
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="任务名称" name="name">
            <a-input v-model:value="form.name" placeholder="请输入任务名称" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="执行类型" name="type">
            <a-select v-model:value="form.type" placeholder="选择执行类型">
              <a-select-option value="command">命令</a-select-option>
              <a-select-option value="script">脚本文件</a-select-option>
              <a-select-option value="executable">可执行程序</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item label="执行命令/路径" name="command">
        <a-input
          v-model:value="form.command"
          :placeholder="getCommandPlaceholder()"
        />
      </a-form-item>

      <a-form-item label="工作目录" name="workingDir">
        <a-input
          v-model:value="form.workingDir"
          placeholder="任务执行时的工作目录（可选）"
        />
      </a-form-item>

      <a-form-item label="调度规则" name="schedule">
        <a-row :gutter="8">
          <a-col :span="16">
            <a-input
              v-model:value="form.schedule"
              placeholder="Cron表达式，例如：0 */30 * * * 表示每30分钟执行一次"
            />
          </a-col>
          <a-col :span="8">
            <a-button @click="showCronHelper = true">Cron助手</a-button>
          </a-col>
        </a-row>
      </a-form-item>

      <a-form-item label="任务描述" name="description">
        <a-textarea
          v-model:value="form.description"
          placeholder="任务描述（可选）"
          :rows="3"
        />
      </a-form-item>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="超时时间（秒）" name="timeout">
            <a-input-number
              v-model:value="form.timeout"
              :min="1"
              :max="86400"
              placeholder="任务执行超时时间"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="重试次数" name="retries">
            <a-input-number
              v-model:value="form.retries"
              :min="0"
              :max="10"
              placeholder="失败时重试次数"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item>
        <a-checkbox v-model:checked="form.enabled">启用任务</a-checkbox>
      </a-form-item>

      <a-form-item>
        <a-space>
          <a-button type="primary" html-type="submit" :loading="submitting">
            {{ isEdit ? '更新' : '创建' }}
          </a-button>
          <a-button @click="goBack">取消</a-button>
        </a-space>
      </a-form-item>
    </a-form>

    <!-- Cron助手模态框 -->
    <a-modal
      v-model:open="showCronHelper"
      title="Cron表达式助手"
      width="600px"
      @ok="showCronHelper = false"
      :maskClosable="false"
    >
      <div class="cron-helper">
        <a-descriptions title="常用Cron表达式示例" :column="1" size="small">
          <a-descriptions-item label="每分钟">* * * * *</a-descriptions-item>
          <a-descriptions-item label="每小时">0 * * * *</a-descriptions-item>
          <a-descriptions-item label="每天0点">0 0 * * *</a-descriptions-item>
          <a-descriptions-item label="每周一0点">0 0 * * 1</a-descriptions-item>
          <a-descriptions-item label="每月1号0点">0 0 1 * *</a-descriptions-item>
          <a-descriptions-item label="每30分钟">0,30 * * * *</a-descriptions-item>
          <a-descriptions-item label="工作日9点">0 9 * * 1-5</a-descriptions-item>
        </a-descriptions>
        <div class="cron-format">
          <p><strong>Cron表达式格式：</strong></p>
          <p>分钟(0-59) 小时(0-23) 日(1-31) 月(1-12) 星期(0-7，0和7都表示周日)</p>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { message } from 'ant-design-vue'
import { ArrowLeftOutlined } from '@ant-design/icons-vue'

const router = useRouter()
const route = useRoute()

const formRef = ref()
const submitting = ref(false)
const showCronHelper = ref(false)
const isEdit = ref(false)

const form = reactive({
  name: '',
  type: 'command',
  command: '',
  workingDir: '',
  schedule: '',
  description: '',
  timeout: 300,
  retries: 0,
  enabled: true
})

const rules = {
  name: [
    { required: true, message: '请输入任务名称', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择执行类型', trigger: 'change' }
  ],
  command: [
    { required: true, message: '请输入执行命令或路径', trigger: 'blur' }
  ],
  schedule: [
    { required: true, message: '请输入Cron表达式', trigger: 'blur' },
    { pattern: /^(\*|[0-5]?\d)(\s+(\*|[01]?\d|2[0-3]))(\s+(\*|[012]?\d|3[01]))(\s+(\*|[01]?\d))(\s+(\*|[0-7]))$/, message: '请输入有效的Cron表达式', trigger: 'blur' }
  ]
}

const getCommandPlaceholder = () => {
  switch (form.type) {
    case 'command':
      return '例如：python script.py 或 node app.js'
    case 'script':
      return '例如：/path/to/script.sh 或 C:\\scripts\\backup.bat'
    case 'executable':
      return '例如：/usr/bin/rsync 或 C:\\Program Files\\app\\app.exe'
    default:
      return '请输入执行命令或路径'
  }
}

const goBack = () => {
  router.push('/tasks')
}

const handleSubmit = async () => {
  submitting.value = true
  try {
    // TODO: 调用API保存任务
    message.success(`任务${isEdit.value ? '更新' : '创建'}成功`)
    goBack()
  } catch (error) {
    message.error(`任务${isEdit.value ? '更新' : '创建'}失败`)
  } finally {
    submitting.value = false
  }
}

const loadTask = async (id: string) => {
  try {
    // TODO: 从API加载任务数据
    // 模拟数据
    if (id === '1') {
      Object.assign(form, {
        name: '数据备份',
        type: 'command',
        command: 'python backup.py',
        workingDir: '/opt/backup',
        schedule: '0 2 * * *',
        description: '每日凌晨2点执行数据备份',
        timeout: 600,
        retries: 2,
        enabled: true
      })
    }
  } catch (error) {
    message.error('加载任务数据失败')
    goBack()
  }
}

onMounted(() => {
  const taskId = route.params.id
  if (taskId) {
    isEdit.value = true
    loadTask(taskId as string)
  }
})
</script>

<style lang="less" scoped>
.task-form {
  max-width: 800px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.cron-helper {
  margin-top: 16px;
}

.cron-format {
  margin-top: 16px;
  padding: 12px;
  background: #f5f5f5;
  border-radius: 4px;
}

.cron-format p {
  margin: 0;
  font-size: 14px;
}
</style> 